package com.xishu.util;

import com.xishu.config.Config;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

public class RedisCachePool {
    private static Logger logger = LoggerFactory.getLogger(RedisCachePool.class);

    private static RedisCachePool instance = new RedisCachePool();

    private JedisPool pool = null;

    private RedisCachePool() {

    }

    public static RedisCachePool getInstance() {
        return instance;
    }

    static {
        instance.init();
    }

    public void init() {
        //创建jedis池配置实例
        JedisPoolConfig poolConfig = new JedisPoolConfig();

        Config config = Config.getInstance();
        //设置池配置项值
        poolConfig.setMaxTotal(config.getInt("jedis.pool.maxActive"));
        poolConfig.setMaxIdle(config.getInt("jedis.pool.maxIdle"));
        poolConfig.setMinIdle(config.getInt("jedis.pool.minIdle"));
        poolConfig.setMaxWaitMillis(config.getInt("jedis.pool.maxWait"));
        poolConfig.setTestOnBorrow(config.getBool("jedis.pool.testOnBorrow"));
        poolConfig.setTestOnReturn(config.getBool("jedis.pool.testOnReturn"));
        logger.info("config is {}", poolConfig);

        if (config.deployCluster()) {
            logger.info("init cluster mode");
            pool = new JedisPool(poolConfig, config.getRedisServer(), config.getRedisPort(), Protocol.DEFAULT_TIMEOUT, null, true);
        } else {
            logger.info("init single mode");
            pool = new JedisPool(poolConfig, config.getRedisServer(), config.getRedisPort(), Protocol.DEFAULT_TIMEOUT, config.getRedisPassword());
        }
    }

    public Jedis getConnection() {
        return pool.getResource();
    }

    public void returnConnection(Jedis jedis) {
        IOUtils.closeQuietly(jedis);
    }

    public void close() {
        IOUtils.closeQuietly(pool);
    }

}
